package repository

import (
	"cr.org/db"
	"cr.org/model"
	"errors"
	"fmt"
	"gorm.io/gorm"
)

type userRepository struct{}

func (r userRepository) userExist(k, v string) (*model.User, bool) {
	user := new(model.User)
	if err := db.GetDB().Where(k+"=?", v).First(&user).Error; !errors.Is(err, gorm.ErrRecordNotFound) {
		return user, true
	}
	return nil, false
}

func (r userRepository) UsernameExist(username string) (*model.User, bool) {
	return r.userExist("username", username)
}

func (r userRepository) FindUserByAccount(username string) (user *model.User, err error) {
	if err = db.GetDB().Where("username = ?", username).Find(&user).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, fmt.Errorf("user not exist")
	}
	return
}

func (r userRepository) AddUser(arg model.User) (err error) {
	_, b := r.UsernameExist(arg.Username)
	if b {
		err = errors.New("用户名已经存在")
		return err
	}
	err = db.GetDB().Save(&arg).Error
	return err
}

func (r userRepository) UpdatePwd(uid int64, oldPwd, newPwd string) (err error) {
	var u model.User
	err = db.GetDB().Where("uid = ?", uid).Find(&u).Error
	if err != nil {
		return err
	}
	u.Password = newPwd
	err = db.GetDB().Save(&u).Error
	return err
}
